use std::sync::{Arc, LazyLock};
use rbatis::intercept_log::LogInterceptor;
use rbatis::RBatis;
use rbdc_pg::PgDriver;
use salvo::conn::TcpListener;
use salvo::{Listener, Server};
use redis::Client;
use crate::core::config::AppConfig;
use crate::routers;

pub mod config;

pub static BANNER: &'static str = r#"
.-.              .-.                                  _
: :              : :.-.                              :_;
: :  .-..-. .--. : `'.'.-..-.   _____    .--.  .---. .-.
: :_ : :; :'  ..': . `.: :; :  :_____:  ' .; ; : .; `: :
`.__;`.__.'`.__.':_;:_;`._. ;           `.__,_;: ._.':_;
                        .-. :                  : :
                        `._.'                  :_;
>>> Lucky Api 接口管理平台
"#;

#[derive(Debug)]
pub struct Context {
    cfg: AppConfig,
    pub db: RBatis,
    pub rd: Client,
    pub banner: &'static str
}

pub static CTX: LazyLock<Context> = LazyLock::new(|| Context::default());

impl Default for Context {
    fn default() -> Self {
        let cfg = AppConfig::default();
        let pg_url = cfg.db.link();
        let redis_url = cfg.redis.link();
        let db = RBatis::new();
        db.intercepts.push(Arc::new(LogInterceptor::new(log::LevelFilter::Info)));
        db.init(PgDriver {}, pg_url.as_str()).unwrap();
        tracing::info!("PG数据初始化完成: {}", pg_url);
        let client = Client::open(cfg.redis.link()).unwrap();
        client.get_connection().expect("连接redis失败");
        tracing::info!("Redis数据连接完成: {}", redis_url);
        Self {
            cfg,
            db,
            rd: client,
            banner: BANNER,
        }
    }
}

pub fn init() {
    println!("{}", CTX.banner);
    tracing_subscriber::fmt().init();
    tracing::info!("Api接口管理服务启动: {}", CTX.cfg.local_addr());
}

pub async fn start() {
    init();
    let acceptor = TcpListener::new(CTX.cfg.local_addr()).bind().await;
    let router = routers::init_routes();
    tracing::info!("路由初始化完成");
    Server::new(acceptor).serve(router).await;
}